package com.speech.activity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.speech.EventListener;
import com.baidu.speech.EventManager;
import com.baidu.speech.EventManagerFactory;
import com.baidu.speech.asr.SpeechConstant;
import com.ontbee.legacyforks.cn.pedant.SweetAlert.SweetAlertDialog;
import com.speech.R;
import com.speech.net.BasicCallBack;
//import com.speech.net.HttpCommunicationManager;
import com.speech.net.constant.EnumReqestActionCode;
import com.speech.net.entity.MessageC2S;
import com.speech.net.entity.MessageC2SBuilder;
import com.speech.net.entity.MessageS2C;
import com.speech.net.request.UserReadingDone_Request;
import com.speech.net.result.Property_Result;
import com.speech.net.result.RequestSentence_Result;
import com.speech.utils.AudioManager;
import com.speech.utils.AutoCheck;
import com.speech.utils.JsonProcessor;
import com.speech.utils.PropertyAndUserInfoHolder;
import com.speech.utils.PropertyTodayDataHolder;
import com.speech.utils.SentenceHolder;
import com.speech.utils.SuperMissionUtil;
import com.speech.utils.TitleBuilder;

import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.LinkedHashMap;
import java.util.Map;

import jaygoo.widget.wlv.WaveLineView;

public class MiningActivity extends BaseActivity implements EventListener {

    private ImageView img_audio;

    private WaveLineView wave_view;

    private TextView tv_current_receive_coin;
    private TextView tv_target_sentence;
    private TextView tv_tip;

    private TextView tv_mission_begin;
    private TextView tv_mission_end;

    private ProgressBar pb_mission_progress;

    private boolean bReadSuccess = false;
    private boolean bReadDone = true;
    private boolean bReadReady = false;


    private Double dCurReceiveCoin = 0d;

    private RequestSentence_Result curRequestSentence = null;

//    private HttpCommunicationManager mHttpManager;

    private Integer iNextSentence = 0;

    private boolean bTouchAble = true;
    private boolean bCancleAlready = false;

    private static long lReadDistTime = 3000L;//读句子最短时间

    private Integer iBeginNum = 0;
    private Integer iEndNum = 20;

    private Float fYStart = null;

    private Long lTimePressed;

    private EventManager asr;
    private SweetAlertDialog dialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mining);
//        mHttpManager = HttpCommunicationManager.getInstance();
        _initView();

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_NETWORK_STATE) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            String[] permissions = {Manifest.permission.RECORD_AUDIO,
                    Manifest.permission.ACCESS_NETWORK_STATE,
                    Manifest.permission.INTERNET,
                    Manifest.permission.READ_PHONE_STATE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
            };
            ActivityCompat.requestPermissions(this, permissions, 123);
        }

        //TODO:语音处理
//        asr = EventManagerFactory.create(this, "asr");
//        asr.registerListener(this); //  EventListener 中 onEvent方法

        _get_target_sentence();

        img_audio.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                if (!bReadReady && SentenceHolder.strSentence == null) {
                    Log.d("fzw", "语料还未准备就绪");
                    if (bTouchAble) {
                        bTouchAble = false;
                        dialog = new SweetAlertDialog(MiningActivity.this, SweetAlertDialog.WARNING_TYPE)
                                .setTitleText("语料还未准备就绪")
                                .setConfirmText("OK")
                                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                    @Override
                                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                                        bTouchAble = true;
                                        sweetAlertDialog.dismiss();
                                    }
                                });
                                dialog.show();
                    }
                    return true;
                }

                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        fYStart = event.getY();
                        Log.i("fzw", "y:" + fYStart);

                        bCancleAlready = false;

                        Log.d("fzw-audio", "action down!!!!");
                        tv_tip.setText(R.string.mining_tip_pressed);
                        if (!bReadDone) {
                            break;
                        }

                        bReadSuccess = false;
                        bReadDone = false;

                        img_audio.setImageResource(R.drawable.btn_audio_pressed_1x);
                        wave_view.startAnim();

                        AudioManager.getInstance().prepareAudio();

                        lTimePressed = System.currentTimeMillis();

//                        _baidu_start();

                        // 开启一个新线程用来判断录音是否成功
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                while (!bReadDone && !bReadSuccess) {
                                    try {
                                        Thread.sleep(250);
                                        if (AudioManager.getInstance().getVoiceLevel(50) > 1) {
                                            //接受到正常音量
                                            bReadSuccess = true;
                                        }
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }).start();

                        break;
                    case MotionEvent.ACTION_UP:
//                        _baidu_stop();
                        if (bCancleAlready) {
                            break;
                        }
                        tv_tip.setText(R.string.mining_tip_default);

                        Log.d("fzw-audio", "action up!!!!");
                        bReadDone = true;
                        img_audio.setImageResource(R.drawable.btn_audio_defalut_1x);
                        wave_view.stopAnim();
                        AudioManager.getInstance().release();

                        long lTimeDist = System.currentTimeMillis() - lTimePressed;
                        if (bReadSuccess && lTimeDist >= lReadDistTime) {
                            bReadReady = false;
                            bReadSuccess = false;
                            tv_tip.setText(R.string.mining_tip_default);
                            //TODO:上传音频文件（待开发）

                            //返回录音成功消息并加币
                            UserReadingDone_Request req = new UserReadingDone_Request();
                            req.strHash = SentenceHolder.strHash;
                            SentenceHolder.strSentence = null;
                            SentenceHolder.strHash = null;


                            //TODO: 接口请求
//                            MessageC2S msg_c2s = MessageC2SBuilder.buildGeneral_MessageC2S(MiningActivity.this, EnumReqestActionCode.读文本加币, JsonProcessor.StcGetJson(req));
//                            String json = JsonProcessor.StcGetJson(msg_c2s);
//                            mHttpManager.doPost(json, new BasicCallBack(MiningActivity.this, json, new BasicCallBack.BasicCallBackListener() {
//                                @Override
//                                public void success(MessageS2C msg_s2c) {
//                                    Property_Result property_rst = JsonProcessor.StcGetObject(Property_Result.class, msg_s2c.strData);
//
//                                    dCurReceiveCoin += property_rst.dCurrentAdd;
//
//                                    tv_current_receive_coin.setText(new DecimalFormat("0.00").format(dCurReceiveCoin));
//
//                                    PropertyTodayDataHolder.increase(MiningActivity.this, property_rst.dCurrentAdd, property_rst.lServerTime);
//                                    PropertyAndUserInfoHolder.update(property_rst);
//
//                                    int itotal = PropertyAndUserInfoHolder.getTotalReadSentence();
//                                    if (itotal >= iEndNum) {
//                                        iBeginNum = SuperMissionUtil.getMissionBeginNum();
//                                        Integer iCurrentNum = SuperMissionUtil.getMissionCurrentNum(iBeginNum);
//                                        iEndNum = SuperMissionUtil.getMissionEndNum();
//                                        tv_mission_begin.setText(iBeginNum + "");
//                                        tv_mission_end.setText(iEndNum + "");
//
//                                        pb_mission_progress.setMax(iEndNum - iBeginNum);
//                                        pb_mission_progress.setProgress(iCurrentNum);
//                                    }
//                                    pb_mission_progress.setProgress(itotal - iBeginNum);
//                                    //请求下一句
//                                    iNextSentence = 1;
//                                    _get_target_sentence();
//                                }
//
//                                @Override
//                                public void fail(MessageS2C msg_s2c) {
//                                    Toast.makeText(MiningActivity.this, msg_s2c.strMsgUI, Toast.LENGTH_SHORT).show();
//                                }
//                            }));
                        } else {
                            if (!bReadSuccess) {
                                Toast.makeText(MiningActivity.this, "音量太小", Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(MiningActivity.this, "录入失败，请按文本认真阅读", Toast.LENGTH_SHORT).show();
                            }

                        }
                        break;

                    case MotionEvent.ACTION_MOVE:
                        if (Math.abs(fYStart - event.getY()) > 100 && !bCancleAlready) {
                            tv_tip.setText(R.string.mining_tip_default);
                            bCancleAlready = true;
                            bReadDone = true;
                            wave_view.stopAnim();
                            img_audio.setImageResource(R.drawable.btn_audio_defalut_1x);
                            Toast.makeText(MiningActivity.this, "录音已取消", Toast.LENGTH_SHORT).show();
                            AudioManager.getInstance().cancel();
                        }
                        break;
                }
                return true;
            }
        });


    }

    private void _get_target_sentence() {
        if (SentenceHolder.strSentence != null) {
            tv_target_sentence.setText(SentenceHolder.strSentence);
        } else if (!bReadReady && SentenceHolder.strSentence == null) {
            Log.d("fzw", "请求语料");
            String strJsonData = "{\"is_next\":" + iNextSentence + "}";
//            String strJsonData = "{\"is_next\":1}";


            //TODO: 接口请求
//            MessageC2S msg_c2s = MessageC2SBuilder.buildGeneral_MessageC2S(this, EnumReqestActionCode.申请读文本, strJsonData);
//            String json = JsonProcessor.StcGetJson(msg_c2s);
//            mHttpManager.doPost(json, new BasicCallBack(this, json, new BasicCallBack.BasicCallBackListener() {
//                @Override
//                public void success(MessageS2C msg_s2c) {
//                    Log.d("fzw", "语料请求成功");
//                    iNextSentence = 1;
//                    curRequestSentence = JsonProcessor.StcGetObject(RequestSentence_Result.class, msg_s2c.strData);
//                    bReadReady = true;
//                    tv_target_sentence.setText(curRequestSentence.strSentence);
//
//                    if (curRequestSentence.strSentence.length() <= 10) {
//                        lReadDistTime = 2000;
//                    } else {
//                        lReadDistTime = 3000;
//                    }
//
//                    SentenceHolder.strHash = curRequestSentence.strHash;
//                    SentenceHolder.strSentence = curRequestSentence.strSentence;
//                }
//
//                @Override
//                public void fail(MessageS2C msg_s2c) {
//                    Toast.makeText(MiningActivity.this,msg_s2c.strMsgUI,Toast.LENGTH_SHORT).show();
//                }
//            }));
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        wave_view.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        wave_view.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        wave_view.release();
        if (dialog != null){
            dialog.dismissWithAnimation();
        }
    }

    private void _initView() {
        new TitleBuilder(MiningActivity.this).setTitleText("语音挖矿");

        img_audio = findViewById(R.id.img_mining_mic);

        wave_view = findViewById(R.id.waveLine_mining);

        tv_target_sentence = findViewById(R.id.tv_mining_target_sentence);
        tv_tip = findViewById(R.id.tv_mining_tip);

        tv_current_receive_coin = findViewById(R.id.tv_mining_already_get_num);

        tv_mission_begin = findViewById(R.id.tv_mining_mission_begin_num);
        tv_mission_end = findViewById(R.id.tv_mining_mission_end_num);

        pb_mission_progress = findViewById(R.id.pb_mining);

        iBeginNum = SuperMissionUtil.getMissionBeginNum();
        Integer iCurrentNum = SuperMissionUtil.getMissionCurrentNum(iBeginNum);
        iEndNum = SuperMissionUtil.getMissionEndNum();
        tv_mission_begin.setText(iBeginNum + "");
        tv_mission_end.setText(iEndNum + "");

        pb_mission_progress.setMax(iEndNum - iBeginNum);
        pb_mission_progress.setProgress(iCurrentNum);

    }

    private void _baidu_start() {
        Map<String, Object> params = new LinkedHashMap<String, Object>();
        String event = null;
        event = SpeechConstant.ASR_START; // 替换成测试的event

        params.put(SpeechConstant.ACCEPT_AUDIO_VOLUME, false);
        // params.put(SpeechConstant.NLU, "enable");
        // params.put(SpeechConstant.VAD_ENDPOINT_TIMEOUT, 0); // 长语音
        // params.put(SpeechConstant.IN_FILE, "res:///com/baidu/android/voicedemo/16k_test.pcm");
        // params.put(SpeechConstant.VAD, SpeechConstant.VAD_DNN);
        // params.put(SpeechConstant.PROP ,20000);
        // params.put(SpeechConstant.PID, 1537); // 中文输入法模型，有逗号
        // 请先使用如‘在线识别’界面测试和生成识别参数。 params同ActivityRecog类中myRecognizer.start(params);

        // 复制此段可以自动检测错误
        (new AutoCheck(getApplicationContext(), new Handler() {
            public void handleMessage(Message msg) {
                if (msg.what == 100) {
                    AutoCheck autoCheck = (AutoCheck) msg.obj;
                    synchronized (autoCheck) {
                        String message = autoCheck.obtainErrorMessage(); // autoCheck.obtainAllMessage();
                        // 可以用下面一行替代，在logcat中查看代码
                        Log.w("AutoCheckMessage", message);
                    }
                }
            }
        }, false)).checkAsr(params);
        String json = null; // 可以替换成自己的json
        json = new JSONObject(params).toString(); // 这里可以替换成你需要测试的json
        asr.send(event, json, null, 0, 0);
    }

    private void _baidu_stop() {
        asr.send(SpeechConstant.ASR_STOP, null, null, 0, 0); //
    }

    @Override
    public void onEvent(String name, String params, byte[] data, int offset, int length) {
        Log.i("fzw", "baidu onEvent():" + name);
        if (name.equals(SpeechConstant.CALLBACK_EVENT_ASR_PARTIAL)) {

            Log.i("fzw", params);
//            if (params.indexOf("\"best_result\":") > -1 ) {
//
//            }
        }
    }
}
